#
import os
import argparse
from typing import Dict
from matplotlib.image import imread
import matplotlib.pyplot as plt
import numpy as np

class Chp01Sec02(object):
    def __init__(self):
        self.name = ''

    @staticmethod
    def startup(params:Dict = {}) -> None:
        print(f'第1章例2')
        plt.rcParams['figure.figsize'] = [16, 8]
        A = imread(os.path.join('study/ddse/images/d00/g00.jpg'))
        X = np.mean(A, -1); # Convert RGB to grayscale
        img = plt.imshow(X)
        img.set_cmap('gray')
        plt.axis('off')
        plt.show()
        # SVD分解
        U, S, VT = np.linalg.svd(X,full_matrices=False)
        S = np.diag(S)
        j = 0
        # 比较不同rank下图片压缩质量
        for r in (5, 20, 100):
            # Construct approximate image
            Xapprox = U[:,:r] @ S[0:r,:r] @ VT[:r,:]
            plt.figure(j+1)
            j += 1
            img = plt.imshow(Xapprox)
            img.set_cmap('gray')
            plt.axis('off')
            plt.title('r = ' + str(r))
            plt.show()
        # x轴为下标序号，y轴为特征值的对数值
        plt.figure(1)
        plt.semilogy(np.diag(S))
        plt.title('Singular Values')
        plt.show()
        # x轴表示求和的特征值数，y轴表示当前求和特征值的和与所有特征值的和之比
        # 可以用于确定rank值
        plt.figure(2)
        plt.plot(np.cumsum(np.diag(S))/np.sum(np.diag(S)))
        plt.title('Singular Values: Cumulative Sum')
        plt.show()


def main(params:Dict = {}) -> None:
    Chp01Sec02.startup(params=params)

def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--run_mode', action='store',
        type=int, default=1, dest='run_mode',
        help='run mode'
    )
    return parser.parse_args()

if '__main__' == __name__:
    args = parse_args()
    params = vars(args)
    main(params=params)



